package com.course.oauth2.controller;

import com.course.common.model.vo.SignInUserInfo;
import com.course.common.response.BaseResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 用户中心
 * @Author: 涂玄武
 * @DATE: 2021/6/22 9:58
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private RedisTokenStore redisTokenStore;

    /**
     * 根据access_token获取当前登录用户信息
     * @param authentication
     * @return
     */
    @GetMapping("me")
    public BaseResponse getCurrentUser(Authentication authentication){
        //转为前端可用的视图对象
        SignInUserInfo dinerInfo = new SignInUserInfo();
        //获取登录用户的信息，然后设置
        BeanUtils.copyProperties(authentication.getPrincipal(), dinerInfo);
        return new BaseResponse().success(dinerInfo);
    }

    //http://127.0.0.1:9009/oauth2-server/user/me?access_token=5939ecbd-863b-49e3-8c75-9255e2f622c8

    /**
     * 安全退出
     *
     * @param access_token
     * @param authorization
     * @return
     */
    @GetMapping("user/logout")
    public BaseResponse logout(String access_token, String authorization) {
        // 判断 access_token 是否为空，为空将 authorization 赋值给 access_token
        if (StringUtils.isBlank(access_token)) {
            access_token = authorization;
        }
        // 判断 authorization 是否为空
        if (StringUtils.isBlank(access_token)) {
            return new BaseResponse().success("退出成功");
        }
        // 判断 bearer token 是否为空
        if (access_token.toLowerCase().contains("bearer ".toLowerCase())) {
            access_token = access_token.toLowerCase().replace("bearer ", "");
        }
        // 清除 redis token 信息
        OAuth2AccessToken oAuth2AccessToken = redisTokenStore.readAccessToken(access_token);
        if (oAuth2AccessToken != null) {
            redisTokenStore.removeAccessToken(oAuth2AccessToken);
            OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
            redisTokenStore.removeRefreshToken(refreshToken);
        }
        return new BaseResponse().success("退出成功");
    }

}
